from flask_restful import fields
import re
import string
import random
import hashlib
from datetime import datetime

# 日期格式化
class formatDate(fields.Raw):
    def format(self, value):
        return value.strftime("%Y-%m-%d %H:%M:%S")

# 正则验证邮箱
def vail_email(email_str):
    reg = r'^[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+){0,4}@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+){0,4}$'
    if re.match(reg, email_str):
        return email_str
    else:
        raise ValueError("邮箱格式不正确")

# 正则验证手机号
def vail_phone(phone_str):
    reg = r'^1[3456789]\d{9}'
    if re.match(reg, phone_str):
        return phone_str
    else:
        raise ValueError("手机号格式不正确")

# 正则验证密码格式
def vail_pwd(pwd_str):
    reg = r'^(?:(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])).{6,15}$'
    if re.match(reg,pwd_str):
        return pwd_str
    else:
        raise ValueError("密码格式不正确")

# 生成随机字符串
def make_crypt(size=6):
    return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(size))

# 生成密码
def make_pwd(pwd = '',crypt=''):
    # 创建md5对象
    hl = hashlib.md5()
    # 此处必须声明encode
    # 否则报错为：hl.update(str)    Unicode-objects must be encoded before hashing
    hl.update((pwd + crypt).encode(encoding='utf-8'))
    hl.update((hl.hexdigest() + crypt).encode(encoding='utf-8'))
    return hl.hexdigest()

# 生成密码


def make_token(admin_id='', admin_name=''):
    # 创建md5对象
    hl = hashlib.md5()
    # 此处必须声明encode
    # 否则报错为：hl.update(str)    Unicode-objects must be encoded before hashing
    hl.update((str(admin_id) + '-smz-' + admin_name).encode(encoding='utf-8'))
    hl.update((hl.hexdigest() + str(datetime.now().timestamp())).encode(encoding='utf-8'))
    return hl.hexdigest()

# 抛出异常信息格式化
def abort_msg(e):
    return str(e).split(': ')[-1]
